import { useEffect, useState } from "react";
import { Button, message, Pagination, Popconfirm, Space, Table, Tooltip } from "antd";
import ServiceCreate from "../../../components/console/governance/serviceCreate";
import { DeleteOutlined, EditOutlined, EyeOutlined, PlusCircleOutlined, CheckCircleOutlined } from "@ant-design/icons";
import ServiceSearch from "../../../components/console/governance/serviceSearch";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import {useNavigate} from "react-router-dom";

/**
 * 服务治理页面
 * @returns {JSX.Element}
 * @constructor
 */
const ServiceGovernancePage = () => {

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();

    // 创建服务信息模态框开关
    const [createServiceVisible, setCreateServiceVisible] = useState(false);

    // 分页部分请求参数
    const [paginationReq, setPaginationReq] = useState({
        pageNum: 1,
        pageSize: 10
    });

    // 分页查询服务治理信息请求参数
    const [pageQueryServiceReq, setPageQueryServiceReq] = useState({
        serviceTitle: '',
        frontBackType: ''
    });

    // 分页查询服务结果
    const [pageQueryServiceResp, setPageQueryServiceResp] = useState({
        total: 0,
        pageCount: 1,
        records: []
    })

    // 服务类型颜色映射
    const serviceTypeColorMap = {
        '前端': {
            text: '#722ed1',
            bg: 'rgba(114, 46, 209, 0.08)'
        },
        '后端': {
            text: '#1890ff',
            bg: 'rgba(24, 144, 255, 0.08)'
        }
    };

    // 健康实例数颜色映射
    const healthyCountColorMap = (count) => {
        if (count === 0) return { text: '#f5222d', bg: 'rgba(245, 34, 45, 0.08)' };
        if (count < 3) return { text: '#fa8c16', bg: 'rgba(250, 140, 22, 0.08)' };
        return { text: '#52c41a', bg: 'rgba(82, 196, 26, 0.08)' };
    };

    // 定义分页列表字段
    const pageServiceRespFields = [
        {
            title: "序号",
            key: "index",
            width: 80,
            align: 'center',
            render: (text, record, index) => {
                return (
                    <div style={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: '#666',
                        fontWeight: 500,
                        fontSize: '14px'  // 增大序号字体
                    }}>
                        {(paginationReq.pageNum - 1) * paginationReq.pageSize + index + 1}
                    </div>
                )
            },
            isShow: true
        }, {
            title: "id",
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            isShow: false
        }, {
            title: "服务标题",
            dataIndex: 'serviceTitle',
            key: 'serviceTitle',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    fontWeight: 600,
                    color: '#1890ff',  // 服务标题设置为蓝色
                    fontSize: '15px',  // 增大标题字体
                    lineHeight: 1.5
                }}>
                    {text}
                </div>
            )
        }, {
            title: '服务名',
            dataIndex: 'serviceName',
            key: 'serviceName',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#ff007f',
                    fontFamily: 'SFMono-Regular, Consolas, monospace',
                    fontSize: '14px'  // 增大服务名字体
                }}>
                    {text}
                </div>
            )
        }, {
            title: '服务描述',
            dataIndex: 'serviceDescription',
            key: 'serviceDescription',
            align: 'center',
            isShow: true,
            render: (text) => (
                // 添加Tooltip显示完整描述
                <Tooltip
                    title={text || '无描述信息'}
                    placement="top"
                    mouseEnterDelay={0.3}  // 延迟显示，避免误触
                    style={{ fontSize: '14px' }}
                >
                    <div style={{
                        color: '#6b7280',
                        fontSize: '14px',  // 增大描述字体
                        lineHeight: 1.4,
                        maxWidth: 200,
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        cursor: 'help'  // 鼠标变为帮助图标，提示可查看详情
                    }}>
                        {text || '-'}
                    </div>
                </Tooltip>
            )
        }, {
            title: '服务类型',
            dataIndex: 'frontBackType',
            key: 'frontBackType',
            align: 'center',
            isShow: false
        }, {
            title: '服务类型枚举值',
            dataIndex: 'frontBackTypeValue',
            key: 'frontBackTypeValue',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    display: 'inline-block',
                    padding: '3px 10px',
                    borderRadius: '12px',
                    color: serviceTypeColorMap[text]?.text || '#4e5969',
                    backgroundColor: serviceTypeColorMap[text]?.bg || 'rgba(0,0,0,0.05)',
                    fontSize: '13px',  // 增大类型标签字体
                    fontWeight: 500
                }}>
                    {text}
                </div>
            )
        }, {
            title: '项目管理员用户id',
            dataIndex: 'projectManager',
            key: 'projectManager',
            align: 'center',
            isShow: false
        }, {
            title: '项目管理员',
            dataIndex: 'projectManagerNickname',
            key: 'projectManagerNickname',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#009999',
                    fontSize: '14px',  // 增大管理员名字体
                    fontWeight: 500
                }}>
                    {text || '-'}
                </div>
            )
        }, {
            title: '健康实例数',
            dataIndex: 'healthyInstanceCount',
            key: 'healthyInstanceCount',
            align: 'center',
            isShow: true,
            render: (count) => {
                const style = healthyCountColorMap(count);
                return (
                    <div style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        padding: '3px 10px',
                        borderRadius: '12px',
                        color: style.text,
                        backgroundColor: style.bg,
                        fontSize: '14px',  // 增大实例数字体
                        fontWeight: 600
                    }}>
                        <CheckCircleOutlined style={{
                            fontSize: '13px',
                            marginRight: '4px'
                        }} />
                        {count}
                    </div>
                )
            }
        }, {
            title: '操作',
            align: 'center',
            render: (text, record) => (
                <Space size="small">
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EyeOutlined />}
                        style={{
                            fontSize: '14px',  // 保持操作按钮字体
                            color: '#1890ff',
                            backgroundColor: 'rgba(24, 144, 255, 0.05)',
                            border: '1px solid #91d5ff',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => {
                            navigate('/console/governance/search/' + record.id)
                        }}
                    >
                        查看
                    </Button>
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EditOutlined />}
                        style={{
                            fontSize: '14px',
                            color: '#fa8c16',
                            backgroundColor: 'rgba(250, 140, 22, 0.05)',
                            border: '1px solid #ffbb96',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(250, 140, 22, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => {
                            navigate('/console/governance/edit/' + record.id)
                        }}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        placement="leftTop"
                        title={"删除服务信息确认"}
                        description={"是否确认要删除该条服务信息？删除的数据将不可恢复。"}
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => removeServiceGovernanceById(record.id)}
                    >
                        <Button
                            size={"small"}
                            type="text"
                            icon={<DeleteOutlined />}
                            style={{
                                fontSize: '14px',
                                color: '#ff0000',
                                backgroundColor: '#FFEBEB',
                                border: '1px solid #ffbb96',
                                borderRadius: '6px',
                                padding: '4px 12px',
                                transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                display: 'inline-flex',
                                alignItems: 'center',
                                gap: '4px'
                            }}
                            onMouseEnter={(e) => {
                                e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.1)';
                                e.target.style.transform = 'translateY(-2px)';
                                e.target.style.boxShadow = '0 2px 8px rgba(250, 140, 22, 0.2)';
                            }}
                            onMouseLeave={(e) => {
                                e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.05)';
                                e.target.style.transform = 'translateY(0)';
                                e.target.style.boxShadow = 'none';
                            }}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
            isShow: true
        }
    ]

    // 表格行样式 - 交替行背景色
    const getRowClassName = (record, index) => {
        return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
    };

    /**
     * 分页查询服务治理信息
     */
    const pageQueryServiceGovernance = () => {
        RequestUtils.post(RequestApis.serviceGovernance.page, {
            ...paginationReq,
            ...pageQueryServiceReq
        }).then(res => {
            setPageQueryServiceResp(res.data.data);
        }).catch(err => messageApi.error(err.message || '服务查询失败'))
    }

    /**
     * 根据id删除服务治理信息
     */
    const removeServiceGovernanceById = (id) => {
        RequestUtils.post(RequestApis.serviceGovernance.removeById, {
            id: id
        }).then(res => {
            pageQueryServiceGovernance();
            messageApi.success("删除服务信息成功");
        }).catch(err => messageApi.error(err.message));
    }

    /**
     * 分页条件改变时立即触发分页查询
     */
    useEffect(() => {
        pageQueryServiceGovernance();
        // eslint-disable-next-line
    }, [paginationReq])

    return (
        <div>
            {contextHolder}

            {/* 查询条件 */}
            <div style={{
                padding: '16px', paddingBottom: '8px'
            }}>
                <ServiceSearch
                    setPaginationReq={setPaginationReq}
                    pageQueryServiceReq={pageQueryServiceReq}
                    setPageQueryServiceReq={setPageQueryServiceReq}
                    pageQueryServiceGovernance={pageQueryServiceGovernance}
                />
            </div>

            <div style={{ marginBottom: "12px" }}>
                <Button
                    color="purple"
                    variant="solid"
                    style={{ width: '240px' }}
                    onClick={() => setCreateServiceVisible(true)}
                >
                    <PlusCircleOutlined style={{marginRight: '10px'}}/>
                    新增服务信息
                </Button>
            </div>

            {/* 新增服务信息模态框 */}
            <ServiceCreate
                visible={createServiceVisible}
                setVisible={setCreateServiceVisible}
                pageQueryServiceGovernance={pageQueryServiceGovernance}
            />

            {/* 表格展示 */}
            <div style={{
                backgroundColor: '#fff',
                borderRadius: '8px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.04)',
                overflow: 'hidden',
                transition: 'box-shadow 0.3s ease'
            }} onMouseOver={(e) => {
                e.currentTarget.style.boxShadow = '0 4px 16px rgba(0, 0, 0, 0.08)';
            }} onMouseOut={(e) => {
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.04)';
            }}>
                <Table
                    dataSource={pageQueryServiceResp.records}
                    columns={pageServiceRespFields.filter(item => item.isShow)}
                    pagination={false}
                    scroll={{
                        y: 'calc(100vh - 470px)',
                        x: 'max-content'
                    }}
                    bordered={false}
                    rowHoverable
                    style={{ width: '100%' }}
                    tableLayout="fixed"
                    rowClassName={getRowClassName}
                    headerStyle={{
                        backgroundColor: '#f5f7fa',
                        color: '#1f2329',
                        fontWeight: 600,
                        fontSize: '15px',  // 增大表头字体
                        borderBottom: '1px solid #e5e6eb',
                        padding: '14px 16px'
                    }}
                    bodyStyle={{
                        fontSize: '14px'  // 统一表格内容字体大小
                    }}
                    rowStyle={{
                        height: '70px',  // 适当增加行高，配合字体大小
                        transition: 'background-color 0.2s ease'
                    }}
                    styles={{
                        table: {
                            '& .table-row-even': {
                                backgroundColor: '#fcfcfc'
                            },
                            '& .table-row-odd': {
                                backgroundColor: '#fff'
                            }
                        }
                    }}
                    onRow={(record, index) => ({
                        onMouseEnter: (e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(24, 144, 255, 0.03)';
                        },
                        onMouseLeave: (e) => {
                            const isEven = index % 2 === 0;
                            e.currentTarget.style.backgroundColor = isEven ? '#fcfcfc' : '#fff';
                        },
                    })}
                />
            </div>

            {/* 分页组件 */}
            <div style={{
                display: "flex",
                justifyContent: "flex-end",
                alignItems: "center",
                height: '60px',
                marginTop: '16px',
                fontSize: '14px'  // 增大分页区域字体
            }}>
                <Pagination
                    total={pageQueryServiceResp.total}
                    current={paginationReq.pageNum}
                    pageSize={paginationReq.pageSize}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => {
                        return (
                            <div style={{ fontSize: '15px' }}>
                                <span>共</span>
                                <span style={{ color: 'red', fontWeight: 'bold' }}> {total} </span>
                                <span>条数据</span>
                            </div>
                        )
                    }}
                    pageSizeOptions={['10', '20', '50', '100', '200']}
                    onChange={(pageNum, pageSize) => {
                        setPaginationReq({
                            ...paginationReq,
                            pageNum: pageNum,
                            pageSize: pageSize
                        })
                    }}
                    onShowSizeChange={(current, size) => {
                        setPaginationReq({
                            ...paginationReq,
                            pageNum: current,
                            pageSize: size
                        })
                    }}
                    style={{
                        padding: '8px 16px'
                    }}
                    itemStyle={{
                        borderRadius: '4px',
                        margin: '0 2px',
                        transition: 'all 0.2s ease'
                    }}
                    prevIcon={<span style={{ transition: 'transform 0.2s ease' }}>←</span>}
                    nextIcon={<span style={{ transition: 'transform 0.2s ease' }}>→</span>}
                />
            </div>

        </div>
    );
}
export default ServiceGovernancePage;